package com.blandware.atleap.webapp.taglib.core.menu.context;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.io.StringWriter;

/**
 * <p>This class implements all common functionality of ItemPart. It renders
 * its body if and only if <b>enabled</b> matches <code>enabled</code> attribute
 * of parent <em>item</em> tag.
 * </p>
 * <p>
 * Note: tag body may be rendered twice: first time for including in context
 * menu, second time for including in page (of needed).
 * </p>
 * <p><a href="ItemPartSupport.java.html"><i>View Source</i></a></p>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.4 $ $Date: 2006/08/03 10:08:25 $
 */
public class ItemPartSupport extends SimpleTagSupport implements ItemPart {

	/**
	 * Internal flag to decide, where to render body content
	 */
	protected int renderingFlag = FLAG_RENDER_TO_PAGE;

	/**
	 * Internal flag initialized by tags which extend this one. Used to
     * determine, whether or not to process body content
	 */
	protected boolean enabled = false;

	/**
	 * Creates new instance of ItemPartSupport
	 */
	public ItemPartSupport() {
	}

	/**
	 * @see ItemPart#getRenderingFlag()
	 */
	public int getRenderingFlag() {
		return renderingFlag;
	}

	/**
	 * Performs tag logic
	 *
	 * @throws javax.servlet.jsp.JspException
	 * @throws java.io.IOException
	 */
	public void doTag() throws JspException, IOException {

		// search for parent item tag
		ItemTag parentItemTag = (ItemTag) findAncestorWithClass(this, ItemTag.class);
		if ( parentItemTag == null ) {
			throw new JspTagException("This tag is only valid when nested within 'item' tag");
		}

		if ( parentItemTag.getEnabled().booleanValue() == enabled ) {
			JspFragment body = getJspBody();
			if ( body != null ) {
				if ( parentItemTag.getIncludeInContextMenu().booleanValue() ) {
					renderingFlag = FLAG_RENDER_TO_MENU;
					StringWriter sw = new StringWriter();
					body.invoke(sw);
					parentItemTag.getItem().setContent(sw.toString().trim());
				}

				if ( parentItemTag.getIncludeInPage().booleanValue() ) {
					renderingFlag = FLAG_RENDER_TO_PAGE;
					body.invoke(null);
				}
			}
		}
	}
}
